package com.kiss.rpc.serialize;

import com.kiss.rpc.config.Wrapper;
import com.kiss.rpc.serialize.impl.JdkSerializer;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class SerializerFactory {
    private final static ConcurrentHashMap<String, Wrapper<Serializer>> SERIALIZE_CACHE = new ConcurrentHashMap<>();
    private final static ConcurrentHashMap<Byte, Wrapper<Serializer>> SERIALIZE_CACHE_CODE = new ConcurrentHashMap<>();

    static {
        Wrapper<Serializer> jdk = new Wrapper<>("jdk", (byte) 1, new JdkSerializer());
        SERIALIZE_CACHE.put(jdk.getName(), jdk);
        SERIALIZE_CACHE_CODE.put(jdk.getCode(), jdk);
    }

    public static Wrapper<Serializer> getSerializer(String serializerType) {
        Wrapper<Serializer> serializer = SERIALIZE_CACHE.get(serializerType);
        if (serializer == null) {
            log.warn("没有找到【{}】序列化工具，默认使用jdk序列化方式", serializerType);
            serializer = SERIALIZE_CACHE.get("jdk");
        }

        return serializer;
    }

    public static Wrapper<Serializer> getSerializer(byte serializerCode) {
        Wrapper<Serializer> serializer = SERIALIZE_CACHE_CODE.get(serializerCode);
        if (serializer == null) {
            log.warn("没有找到编码为【{}】序列化工具，默认使用jdk序列化方式", serializerCode);
            serializer = SERIALIZE_CACHE.get("jdk");
        }

        return serializer;
    }
}
